package com.base.myproject.server.ratify;

import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;

import java.sql.ResultSet;
import java.util.Vector;

import com.base.myproject.server.busi.BusiInfo;
import com.base.myproject.server.database.PoolMan;
import com.base.myproject.server.status.Status;
/**
 * SELECT icode,busicode,busistatus,bcode,formula,tobcode,tostatus,firstlastflag,fromstatus,ratifyicode FROM ratify r;
 *               业务编码   ，无效  单据人 ，公式，审批人，目标状态，第一次提交标识，审批状态，审批内码
 *               
 *  ratify表定义了单据的审批过程，那条记录是一条审批任务，根据单据号找到该审批任务后生成审批的明细到ratifydetail
 *  ratifydetail里保存着各个单据的审批过程。
 *  SELECT icode,ratifyicode,busicode,ratifybcode,bcode,fromstatus,tostatus,ratifystatus FROM ratifydetail 
 *    		内码，审批任务号，业务单据号，审批人，单据人，单据审批前状态，审批后状态，审批标识  
 * @author zgw
 *
 */
public class Ratify {
	static Ratify ratify = null;
	static BusiInfo busiinfo = null;
	String curbcode=null;
	private Ratify(BusiInfo busiinfo, String curbcode) {
		this.curbcode = curbcode;

	}

	synchronized public static Ratify getInstance(BusiInfo busiinfo,
			String curbcode) {
		if (ratify == null) {
			ratify = new Ratify(busiinfo, curbcode);
		}
		ratify.busiinfo = busiinfo;
		return ratify;
	}

	public String doRatify(String action,
			String ratifymessage) throws Exception {
		String str = null;
		PoolMan pm = new PoolMan();
		Vector v = new Vector();
		String ratifyicode = ""; //审批编号
		boolean islastratify=false;
		
		// 检查是否第一次提交
		String sql = "select icode,ratifyicode,busicode,bcode,fromstatus,tostatus,firstlastflag ,formula,tobcode from ratify where busicode='"
				+ busiinfo.getBusicode() + "' and fromstatus='" + busiinfo.getStatus() + "' and bcode like '"+busiinfo.getVprepare()+"%'";
		ResultSet rs = pm.executeQuery(sql);
		String icode = "";
		String busicode = "";
		String firstlastflag = "";
		String formula = "";
		String fromstatus = "";
		String tostatus = "";
		String bcode = "";
		String tobcode ="";
		boolean b = false;
		if (rs.next()) {
			icode = rs.getString("icode");
			ratifyicode = rs.getString("ratifyicode");
			busicode = rs.getString("busicode");
			bcode = rs.getString("bcode");
			
			fromstatus = rs.getString("fromstatus");
			tostatus = rs.getString("tostatus");
			firstlastflag = rs.getString("firstlastflag");
			formula = rs.getString("formula");
			tobcode = rs.getString("tobcode");
			System.out.println("bocde=" + bcode + " fromstatus = " + fromstatus
					+ " firstlastflag=" + firstlastflag + "  formula="
					+ formula);
			b = true;
		}
		//无审批记录
		if(!b)
		{
			return "没有设置人员编码："+busiinfo.getVprepare()+" 状态："+ busiinfo.getStatus() +" 的审批链";
		}
//第一次提交审批任务，改变提交状态，生成审批记录
		if (firstlastflag!=null && firstlastflag.equals("1") ) {
			//if(fromstatus.equals(busiinfo.getStatus()))
			{
			String updatesql = "update "+busiinfo.getTablename()+" set busistatus='" + tostatus
					+ "' where busistatus='"+fromstatus+"' and icode = '"+busiinfo.getIcode()+"'";

			
			//插入审批记录
			String sql2 = "select icode,busicode,bcode,fromstatus,tostatus,firstlastflag ,formula from ratify where busicode='"
				+ busiinfo.getBusicode() + "' and fromstatus='" + tostatus + "' ";
	
			
			ResultSet insertresordrs = pm.executeQuery(sql2);
			String icode2 = "";
			String busicode2 = "";
			String firstlastflag2 = "";
			String formula2 = "";
			String fromstatus2 = "";
			String tostatus2 = "";
			String bcode2 = "";
			while(insertresordrs.next())
			{
				icode2 = insertresordrs.getString("icode");
				busicode2 = insertresordrs.getString("busicode");
				bcode2 = insertresordrs.getString("bcode");
			
				fromstatus2 = insertresordrs.getString("fromstatus");
				tostatus2 = insertresordrs.getString("tostatus");
				firstlastflag2 = insertresordrs.getString("firstlastflag");
				formula2 = insertresordrs.getString("formula");
				islastratify= true; //如果为true那么就是没有新的审批任务，这是最后的审批任务。//zgw 这个有何用？
			}
	//		v.add(updatesql);
			pm.Update(updatesql);
			if(islastratify)
			{
			//@Todo 多个审批没有做
			String insql = "insert into ratifydetail(ratifyicode,busicode,ratifybcode,bcode,fromstatus,tostatus,ratifystatus,busiinnercode)";
			insql += " values('" + ratifyicode + "','" + busicode2 + "','"
					+ tobcode + "','" + bcode2 + "','" + fromstatus2 + "','"
					+ tostatus2 + "','" + Status.RATIFYSTATUS_WAIT + "','"+busiinfo.getIcode()+"')";

			System.out.println(updatesql);
			System.out.println(insql);
	//		v.add(insql);
			pm.Update(insql);
			}
			}
			
		}

//		else if(1==1)
//		{
//			return "";
//		}
		//非第一次提交
		else {
			// 检查是否有未处理的审批任务。
//			String sqlratifydetail = "select busicode,ratifybcode,fromstatus,tostatus,ratifystatus from ratifydetail where fromstatus='"
//					+ busiinfo.getStatus()
//					+ "' and ratifystatus='"
//					+ Status.RATIFYSTATUS_WAIT
//					+ "' and ratifybcode!='"
//					+ ratifybcode + "'";
//
//			System.out.println(sqlratifydetail);
//			ResultSet ratifydetailds = pm.executeQuery(sqlratifydetail);
//
//			StringBuffer sbf = new StringBuffer();
//			tostatus = "";
//			while (ratifydetailds.next()) {
//				sbf.append(ratifydetailds.getString("ratifybcode"));
//				System.out.println(sbf);
//				
//			}
			

			// 当前单据的审批任务,除开当前人的审批任务
			String sqlcurratifydetail = "select count(*) as countnum from ratifydetail where fromstatus='"
					+ busiinfo.getStatus()
					+ "' and ratifystatus='"
					+ Status.RATIFYSTATUS_WAIT
					+ "' and busicode='"
					+ busiinfo.getBusicode() + "' and ratifybcode !='"+busiinfo.getVprepare()+"' and ratifyicode='"+ratifyicode+"' and busiinnercode='"+busiinfo.getIcode()+"'";
			ResultSet ratifycurdetailds = pm.executeQuery(sqlcurratifydetail);
			int countnum = 0;
			while (ratifycurdetailds.next()) {
				countnum = ratifycurdetailds.getInt("countnum");
			}
			

		
			String sqlratifydetail = "select tostatus from ratifydetail where busicode = '"+busiinfo.getBusicode()+"' and ratifybcode='"+busiinfo.getVprepare()+"' and ratifyicode='"+ratifyicode+"' and ratifystatus='"+Status.RATIFYSTATUS_WAIT+"' and busiinnercode='"+busiinfo.getIcode()+"'";
				//在执行pm.Update(updatecursql); 之前查询
			ResultSet ratifyedcurdetailds = pm.executeQuery(sqlratifydetail);
			
			//审批通过当前人的任务 ,更新当前审批人，改业务编码下，审批状态是RATIFYSTATUS_WAIT 的审批任务
			String updatecursql = "update ratifydetail set ratifystatus='"+Status.RATIFYSTATUS_RATIFY+"' where busicode = '"+busiinfo.getBusicode()+"' and ratifybcode='"+busiinfo.getVprepare()+"' and busiinnercode='"+busiinfo.getIcode()+"' and ratifystatus ='"+Status.RATIFYSTATUS_WAIT+"'";
			System.out.println(updatecursql);
			pm.Update(updatecursql);
		//	v.add(updatecursql);
			String curstatus=""; //最后审批状态
			if(ratifyedcurdetailds.next())
			{
				curstatus = ratifyedcurdetailds.getString("tostatus");
			}
			
			
			//如果没有其他人的未审批记录说明该条审批任务已经终结，要生成下一条审批任务
			if(countnum==0)
			{
				
		
				
				//插入审批记录
				String sql2 = "select icode,busicode,bcode,fromstatus,tostatus,firstlastflag ,formula ,tobcode from ratify where busicode='"
					+ busiinfo.getBusicode() + "' and fromstatus='" + curstatus + "' ";
		
				
				ResultSet insertresordrs = pm.executeQuery(sql2);
				String icode2 = "";
				String busicode2 = "";
				String firstlastflag2 = "";
				String formula2 = "";
				String fromstatus2 = "";
				String tostatus2 = "";
				String bcode2 = "";
				String ratifybcode2 = "";
				while(insertresordrs.next())
				{
					icode2 = insertresordrs.getString("icode");
				
					busicode2 = insertresordrs.getString("busicode");
					bcode2 = insertresordrs.getString("bcode");
					fromstatus2 = insertresordrs.getString("fromstatus");
					tostatus2 = insertresordrs.getString("tostatus");
					firstlastflag2 = insertresordrs.getString("firstlastflag");
					formula2 = insertresordrs.getString("formula");
					ratifybcode2 = insertresordrs.getString("to");
					islastratify= true; //如果为true那么就是没有新的审批任务，这是最后的审批任务。
				}
				
				if(islastratify)
				{
				//@Todo 多个审批没有做
				String insql = "insert into ratifydetail(ratifyicode,busicode,ratifybcode,bcode,fromstatus,tostatus,ratifystatus,busiinnercode)";
				insql += " values('" + ratifyicode + "','" + busicode2 + "','"
						+ ratifybcode2+ "','" + bcode2 + "','" + fromstatus2 + "','"
						+ tostatus2 + "','" + Status.RATIFYSTATUS_WAIT + "','"+busiinfo.getIcode()+"')";

				
				System.out.println(insql);
				
				pm.Update(insql);
				//v.add(insql);
				}
				
				
			}
			
			if (formula != null) {
				// BSFManager.registerScriptingEngine("ruby",
				// "org.jruby.javasupport.bsf.JRubyEngine", new String[] { "rb"
				// });
				// BSFManager manager = new BSFManager();
				// manager.declareBean("out", System.out, PrintStream.class);
				// // manager.eval("ruby", "(java)", 1, 1,
				// "$out.println('hello System.out')");
				// manager.eval("ruby", "(java)", 1, 1, formula);
				// Object o =manager.eval("ruby", "(java)", 1, 1,
				// "$out.println('zz')");
				// System.out.println("o=="+o);

				// String name = "zgw";

				ClassLoader parent = getClass().getClassLoader();
				GroovyClassLoader loader = new GroovyClassLoader(parent);
				Class groovyClass = loader
						.parseClass("class Greet {def salute(name) { println \"Hello $name!\" ;return name}}");
				GroovyObject groovyObject = (GroovyObject) groovyClass
						.newInstance();
				Object obj = groovyObject.invokeMethod("salute",
						new Object[] { pm });
				System.out.println(obj);
			}
			// /执行formula，返回 审批人员与审批方式
			// else
			{
				//String icode = "" + MakeCode.makeCode("ratifydetail", "icode");
				// String sql = "select "

			//	String insql = "insert into ratifydetail (ratifyicode,busicode,ratifybcode,bcode,fromstatus,tostatus,ratifystatus) values(1,1,1,1,1,1,1)";
			//	pm.Update(insql);
			}
		}
	//	pm.getConnection("test");
		// pm.handleTransaction(v);
		return "审批完成";
//		return str;
	}
	/**
	 * 取消审批，如果下一级审批任务还没有审批，那么就可以删除下级审批，本级审批状态
	 * 恢复到最开始的状态
	 * @param ratifybcode
	 * @param icode
	 * @return
	 */
	public boolean cancelRatify(String ratifybcode,String icode)
	{
		boolean b=true;
		
		return b;
	}
}
